package org.best.practices.android.rotationasynctask.application;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentName;
import android.os.Bundle;
import android.util.Log;

public class ActivityLifecycleListener implements Application.ActivityLifecycleCallbacks {
    private final static String TAG = ActivityLifecycleListener.class.getSimpleName();
    
    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        Log.d(TAG, LifecycleLogFormatter.generateInformation(activity, "onActivityCreated"));
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        Log.d(TAG, LifecycleLogFormatter.generateInformation(activity, "onActivityDestroyed"));
    }

    @Override
    public void onActivityPaused(Activity activity) {
        Log.d(TAG, LifecycleLogFormatter.generateInformation(activity, "onActivityPaused"));
    }

    @Override
    public void onActivityResumed(Activity activity) {
        Log.d(TAG, LifecycleLogFormatter.generateInformation(activity, "onActivityResumed"));
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        Log.d(TAG, LifecycleLogFormatter.generateInformation(activity, "onActivitySaveInstanceState"));
    }

    @Override
    public void onActivityStarted(Activity activity) {
        Log.d(TAG, LifecycleLogFormatter.generateInformation(activity, "onActivityStarted"));
    }

    @Override
    public void onActivityStopped(Activity activity) {
        Log.d(TAG, LifecycleLogFormatter.generateInformation(activity, "onActivityStopped"));
    }
    
    public static class LifecycleLogFormatter {
        public static String generateInformation(Activity activity, String lifecycleStage) {
            String activityInfo = parseComponentName(activity);
            
            StringBuilder builder = new StringBuilder();
            builder.append(activityInfo);
            builder.append(String.format("Lifecycle Stage: %s", lifecycleStage));
            
            return builder.toString();
        }
        
        public static String parseComponentName(Activity activity) {
            ComponentName componentName = activity.getComponentName();
            
            StringBuilder builder = new StringBuilder();
            
            builder.append("Activity");
            builder.append(":");
            builder.append(String.format("identity: %d", System.identityHashCode(activity)));
            builder.append(",");
            builder.append(String.format("class: %s", componentName.getClassName()));
            
            return builder.toString();
        }
    }
}
